package Admin;

import javax.swing.JPanel;

import java.awt.BorderLayout;
import java.io.File;
import java.io.FileOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JButton;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class DB_Server_Log extends JPanel implements Runnable{
	private JPanel panel;
	private JScrollPane scrollPane;
	JTextArea ta_DBLog;
	private JButton btn_SaveLog;
	ServerSocket db_server;
	boolean flag = true;

	/**
	 * Create the panel.
	 */
	public DB_Server_Log() {
		setLayout(new BorderLayout(0, 0));
		add(getPanel(), BorderLayout.NORTH);
		add(getScrollPane(), BorderLayout.CENTER);
		new Thread(this).start();
	}

	public JPanel getPanel() {
		if (panel == null) {
			panel = new JPanel();
			panel.add(getBtn_SaveLog());
		}
		return panel;
	}
	public JScrollPane getScrollPane() {
		if (scrollPane == null) {
			scrollPane = new JScrollPane();
			scrollPane.setViewportView(getTa_DBLog());
		}
		return scrollPane;
	}
	public JTextArea getTa_DBLog() {
		if (ta_DBLog == null) {
			ta_DBLog = new JTextArea();
			ta_DBLog.setEnabled(false);
			ta_DBLog.setEditable(false);
		}
		return ta_DBLog;
	}
	public JButton getBtn_SaveLog() {
		if (btn_SaveLog == null) {
			btn_SaveLog = new JButton("로그 저장 및 화면 정리");
			btn_SaveLog.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					savelog();
				}
			});
		}
		return btn_SaveLog;
	}

	@Override
	public void run() {
		
		
		try
		{
			db_server = new ServerSocket(12006);
			while(flag)
			{
				Socket s = db_server.accept();
				new DB_Thread(s, ta_DBLog);
			}
			db_server.close();
			db_server = null;
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
	}
	public void savelog()
	{
		try
		{
			long time = System.currentTimeMillis();
			SimpleDateFormat dayTime = new SimpleDateFormat("yyyy_MM_dd_hh_mm_ss");
			String str = dayTime.format(new Date(time));
			
			File f = new File("C:\\manage\\db_log");
			f.mkdirs();
			File ff = new File(f.getPath()+"\\"+str+".txt");
			FileOutputStream fos = new FileOutputStream(ff);
			fos.write(ta_DBLog.getText().getBytes());
			fos.close();
			ta_DBLog.setText("");
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
	}
}
